package pb

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//记录合伙人的收入记录
func NewCashRecord(cr map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	values, sql := InsertSql(TablePbCashRecord, cr)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//更新代理的收入，amount为30加上30,为-30为减去30
func UpdateCash(amount, uid int64, isWithdraw bool, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	var sql string
	if !isWithdraw { //不是提现
		sql = fmt.Sprintf(`UPDATE %v SET amount = amount + %v WHERE uid = %v`,
			TablePbUser, amount, uid)
	} else { //提现
		sql = fmt.Sprintf(`UPDATE %v SET amount = amount + %v,withdraw_time = %v WHERE uid = %v`,
			TablePbUser, amount, time.Now().Unix(), uid)
	}
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//合伙人的提成
func ListCashRecord(p ListParams, uid int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			cr.*,
			u.head_img_url,u.nickname
		FROM
			%v AS cr
		LEFT JOIN
			%v AS u
		ON cr.agent_id = u.uid
		WHERE
			cr.uid = %v
		ORDER BY
			cr.create_time DESC
		LIMIT ?,?
	`, TablePbCashRecord, TablePfUser, uid)
	o := NewOrm(multiOrm, DBChessPartner)
	var cr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cr)
	if CheckError(err) {
		return cr, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE uid = %v`,
		TablePbCashRecord, uid)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return cr, 0, err
	}
	return cr, count, nil
}

//首页展示
func ListHome(uid int64) (orm.Params, error) {

	var (
		todayIncome int64 //今日收入
		todayAgent  int64 //今日新增代理
		todayCharge int64 //今日充值
		todayPlayer int64 //今日新增玩家

		totalIncome int64 //累计提成收入
		totalAgent  int64 //总代理数
		totalCharge int64 //总充值
		totalPlayer int64 //总玩家数
		restIncome  int64 //提成余额

		bonusRate int64 //合伙人分成比例
	)

	o := NewDBOrm(DBChessPartner)
	oc := NewDBOrm(DBChess)
	start, end := GetTodayTimestamp()

	//今日收入
	sql := fmt.Sprintf(`
		SELECT
			IF(SUM(amount) is NULL,0,SUM(amount)) AS today_income
		FROM
			%v
		WHERE
			uid = %v AND type = %v AND create_time >= %v AND create_time < %v
		`, TablePbCashRecord, uid, PfCashAgentBonus, start, end)
	o.Raw(sql).QueryRow(&todayIncome)

	//今日新增代理
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1) AS today_agent
		FROM
			%v
		WHERE
			group_id = %v AND status = %v AND create_time >= %v AND create_time < %v
		`, TablePfUser, uid, PfFirstTopUpSuccess, start, end)
	o.Raw(sql).QueryRow(&todayAgent)

	//今日充值
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(cash) is NULL,0,SUM(cash)) AS today_charge
		FROM
			%v
		WHERE
			uid = %v AND type = %v AND create_time >= %v AND create_time < %v
		`, TablePbCashRecord, uid, PfCashAgentBonus, start, end)
	o.Raw(sql).QueryRow(&todayCharge)

	//今日新增玩家
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1) AS today_player
		FROM
			%v
		WHERE
			group_id = %v AND player != 0 AND activate_time >= %v AND activate_time < %v
		`, TableAgentPlayer, uid, start, end)
	oc.Raw(sql).QueryRow(&todayPlayer)

	//累计提成收入
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(amount) is NULL,0,SUM(amount)) AS total_income
		FROM
			%v
		WHERE
			uid = %v AND type = %v
		`, TablePbCashRecord, uid, PfCashAgentBonus)
	o.Raw(sql).QueryRow(&totalIncome)

	//总代理数
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1) AS total_agent
		FROM
			%v
		WHERE
			group_id = %v AND status = %v
		`, TablePfUser, uid, PfFirstTopUpSuccess)
	o.Raw(sql).QueryRow(&totalAgent)

	//总充值
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(cash) is NULL,0,SUM(cash)) AS total_charge
		FROM
			%v
		WHERE
			uid = %v AND type = %v
		`, TablePbCashRecord, uid, PfCashAgentBonus)
	o.Raw(sql).QueryRow(&totalCharge)

	//总玩家数
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1) AS total_player
		FROM
			%v
		WHERE
			group_id = %v AND player != 0
		`, TableAgentPlayer, uid)
	oc.Raw(sql).QueryRow(&totalPlayer)

	//提成余额,分成比例
	sql = fmt.Sprintf(`
		SELECT
			amount AS rest_income,bonus_rate
		FROM
			%v
		WHERE
			uid = %v
	`, TablePbUser, uid)
	o.Raw(sql).QueryRow(&restIncome, &bonusRate)

	data := map[string]interface{}{
		"today_income": todayIncome,       //今日收入
		"today_agent":  todayAgent,        //今日新增代理
		"today_charge": todayCharge,       //今日充值
		"today_player": todayPlayer,       //今日新增玩家
		"total_agent":  totalAgent,        //总代理数
		"total_player": totalPlayer,       //总玩家数
		"total_charge": totalCharge,       //总充值
		"total_income": totalIncome,       //累计提成收入
		"rest_income":  restIncome,        //提成余额
		"bonus_rate":   10000 - bonusRate, //分成比例
	}
	return data, nil

}
